﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class DBHelper
    {
        public static string ConnString = "server=.;database=Users;Integrated Security = true";
        public static SqlConnection Conn = null;
        public static void InitConnection()
        {
            //如果连接对象不存在，则创建连接对象
            if (Conn == null)
            {
                Conn = new SqlConnection(ConnString);
            }
            //如果连接对象关闭，这打开连接对象
            if (Conn.State == ConnectionState.Closed)
            {
                Conn.Open();
            }
            //如果连接断开，则重新连接
            if (Conn.State == ConnectionState.Broken)
            {
                Conn.Close();
                Conn.Open();
            }
        }
        //查询DataReader
        public static SqlDataReader GetDataReader(string sqlStr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }

        //增删改
        public static bool ExecuteNonQuery(string sqlStr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            int result = cmd.ExecuteNonQuery();
            Conn.Close();
            return result > 0;
        }

        //执行集合函数
        public static object ExecuteScalar(string sqlStr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            object result = cmd.ExecuteScalar();
            Conn.Close();
            return result;
        }

        public static DataTable GetDataTable(string sql)
        {
            InitConnection();
            DataTable dt = new DataTable();
            SqlDataAdapter dap = new SqlDataAdapter(sql, Conn);
            dap.Fill(dt);
            return dt;
        }
    }
}
